package cool.taomu.software.fig.antlr4.entry

import cool.taomu.software.fig.asm.aspect2.AspectUtils
import cool.taomu.software.fig.reflect.ReflectUtils
import org.antlr.v4.runtime.CharStream
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import org.antlr.v4.runtime.Lexer
import org.antlr.v4.runtime.Parser
import org.antlr.v4.runtime.TokenStream
import org.antlr.v4.runtime.tree.ParseTree
import org.antlr.v4.runtime.tree.ParseTreeListener
import org.antlr.v4.runtime.tree.ParseTreeWalker

class Antlr4Entry {
    def static entry(
        Class<? extends Lexer> lexerClass,
        Class<? extends Parser> parseClass,
        Class<? extends ParseTreeListener> ptlistenerClass,
        Class<?> aspectClass,
        String entry,
        String input
    ) {
        var CharStream cs = CharStreams.fromString(input);
        var lexer = ReflectUtils.newInstance(lexerClass, #[CharStream], #[cs]) as Lexer;
        var tokens = new CommonTokenStream(lexer);
        var parser = parseClass.cast(ReflectUtils.newInstance(parseClass, #[TokenStream], #[tokens]));
        var ParseTree tree = ReflectUtils.getMethod(parseClass,entry).invoke(parser) as ParseTree;
        var ParseTreeWalker walker = new ParseTreeWalker();
        var aspect = AspectUtils.instance;
        var clistenermap = aspect.build(aspectClass);
        var ptl = clistenermap.getClass(ptlistenerClass);
        var listener =ReflectUtils.newInstance(ptl) as ParseTreeListener;
        walker.walk(listener, tree);
    }
}
